<template>
    <div >
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="位置名称" prop="locationName">
          <el-input
            v-model="queryParams.locationName"
            placeholder="请输入位置名称"
            clearable
            size="small"
            style="width: 180px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="位置类型" >
          <el-select v-model="queryParams.locationType" clearable>
            <el-option label="楼栋" value="1"></el-option>
            <el-option label="楼层" value="2"></el-option>
            <el-option label="办公室" value="3"></el-option>
            <el-option label="教室" value="4"></el-option>
            <el-option label="实验室" value="5"></el-option>
            <el-option label="宿舍" value="6"></el-option>
            <el-option label="其他" value="7"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增宿舍</el-button>
        </el-col>

        <!-- <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['basedata:bclass:remove']"
          >删除</el-button>
        </el-col> -->

        </el-row>

        <el-table v-loading="loading" :data="bclassList" row-key="id" lazy :load="loadChildData"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column label="序号" align="center" prop="id" />
        <el-table-column label="位置名称" align="center" prop="locationName" :show-overflow-tooltip="true" />
        <el-table-column label="层级名称" align="center" prop="levelName" :show-overflow-tooltip="true" />
        <el-table-column label="是否有效" align="center" prop="status" width="160">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==0" type="danger">无效</el-tag>
            <el-tag v-if="scope.row.status==1" type="success">有效</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="schoolId" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.locationType==1" >楼栋</el-tag>
            <el-tag v-if="scope.row.locationType==2" >楼层</el-tag>
            <el-tag v-if="scope.row.locationType==3" >办公室</el-tag>
            <el-tag v-if="scope.row.locationType==4" >教室</el-tag>
            <el-tag v-if="scope.row.locationType==5" >实验室</el-tag>
            <el-tag v-if="scope.row.locationType==6" >宿舍</el-tag>
            <el-tag v-if="scope.row.locationType==7" >会议室</el-tag>
            <el-tag v-if="scope.row.locationType==99" >其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" >
          <template slot-scope="scope">
            <!-- <el-tooltip class="item" effect="dark" content="新增" placement="top">
              <el-button
                    size="mini"
                    circle type="success"
                    icon="el-icon-plus"
                    @click="handleAdd(scope.row)"

              />
            </el-tooltip> -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <el-button
                    size="mini"
                    circle type="primary"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"

              />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button
                    size="mini"
                    circle type="danger"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"

              />
            </el-tooltip>

          </template>
        </el-table-column>
        </el-table>

        <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        />



      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="30%">
         <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                  <el-form-item label="位置名称" prop="locationName">
                      <el-input v-model="form.locationName" clearable @input="changeName"></el-input>
                  </el-form-item>
                  <el-form-item label="宿舍床位数" prop="seat">
                    <el-input-number v-model="form.seat" @change="inputSeat" :min="1" :max="20" ></el-input-number>
                  </el-form-item>
                  <el-form-item label="宿舍楼栋" prop="locationPid">
                    <!--<el-select v-model="form.locationPid" @change="changePid" clearable style="width:100%">
                        <el-option v-for="item in selectedList" :key="item.id"
                        :label="item.levelName" :value="item.id"></el-option>
                    </el-select>-->
                    <div class="block">
                      <el-cascader
                        v-model="form.locationPid"
                        :options="selectedListName"
                        separator="-"
                        @change="changePid"></el-cascader>
                    </div>
                  </el-form-item>
                  <el-form-item label="层级名称" >
                      <el-input v-model="form.levelName" :disabled="true"></el-input>
                  </el-form-item>
                  <el-form-item label="位置类型" >
                    <!-- <el-radio v-model="form.locationType" label="1">楼栋</el-radio>
                    <el-radio v-model="form.locationType" label="2">楼层</el-radio>
                    <el-radio v-model="form.locationType" label="3">办公室</el-radio>
                    <el-radio v-model="form.locationType" label="4">教室</el-radio>
                    <el-radio v-model="form.locationType" label="5">实验室</el-radio> -->
                    <el-radio v-model="form.locationType" label="6">宿舍</el-radio>
                    <!-- <el-radio v-model="form.locationType" label="7">会议室</el-radio>
                    <el-radio v-model="form.locationType" label="99">其他</el-radio> -->
                  </el-form-item>
                  <el-form-item label="床位编号" v-if="locationList.length>0">
                    <div v-for="item in locationList" :key="item.berthCode">
                        <el-input-number size="mini" v-model="item.berthCode" :min="1" :max="20" style="width:30%" ></el-input-number>
                        <el-select size="mini" v-model="item.berthType" style="width:30%">
                            <el-option value="1" label="上铺"></el-option>
                            <el-option value="2" label="下铺"></el-option>
                            <el-option value="3" label="上铺下桌"></el-option>
                        </el-select>
                        <el-tag v-if="item.useStudentId" type="success">已使用</el-tag>
                        <el-tag v-else type="info">未使用</el-tag>
                    </div>

                  </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>

  <script>
  import { findBaseSpaceLocationPageList, addOrUpdateBaseSpaceLocationInfo, deleteBaseSpaceLocationInfo,getLocationDetails,selectDormitory} from "@/api/baseData/siteManagement";


  export default {
    name: "building",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        stuCount: 0,
        // 字典表格数据
        bclassList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 班主任
        userOptions: [],
        // 状态数据字典
        statusOptions: [],
        // 班级所属部门
        classDeptOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          locationType: 6
        },
        // 表单参数
        form: {
          locationPid: 0
        },
        // 表单校验
        rules: {
            locationName: [{ required: true, message: "请填写位置名称", trigger: "blur" }],
            seat:[{ required: true, message: "请填写宿舍床位数", trigger: "blur" }],
            locationPid:[{ required: true, message: "请选择宿舍楼栋", trigger: "blur" }]
        },
        selectedList:[],
        selectedListName: [],
        schoolList:[],
        locationList:[]
      };
    },
    created() {
      this.getList();

      /*findBaseSpaceLocationPageList({pageNum:1,pageSize:1000,locationType:1,locationPid:0}).then(response => {
        debugger
        this.selectedList = response.data.list;
        this.selectedListName = this.selectedList;
        });*/
    },
    methods: {
      //查楼层↓↓↓
      build(){
        selectDormitory().then(resp => {
          this.selectedList = resp.data;
          this.selectedListName = this.selectedList.map(value => {
            const childNode=value.baseSpaceLocationVOList.map(v=>{
              return {
                value: v.id,
                label: v.locationName
              };
            })
            return {
              value: value.id,
              label: value.locationName,
              children: childNode
            };
          });
        });
      },
      //查楼层↑↑↑
      getSchoolName(id){
        for(let i=0;i<this.schoolList.length;i++){
          if(this.schoolList[i].id==id){
            return this.schoolList[i].schoolName
          }
        }
      },

      changePid(val){            
          if(val){
            if(val.length > 0){
              this.form.locationPid = val[val.length - 1]
            }
            if(this.form.locationName){
              this.selectedListName.forEach(item => {
                if(val.length == 1){
                  item.children.forEach(subItem => {
                    if(subItem.value == val){
                      this.$set(this.form,"levelName", item.label + "-" + this.form.locationName)
                    }
                  })
                }else{
                  if(item.value == val[0]){
                    this.$set(this.form,"levelName", item.label + "-" + this.form.locationName)
                  }
                }
              })
            }
          }
      },
      changeName(){
          this.changePid([this.form.locationPid])
          if(this.form.levelName){
            this.form.levelName = this.form.levelName.split("-")[0] + "-" + this.form.locationName
          }
      },
      /** 查询班级列表 */
      getList() {
        this.loading = true;
        this.bclassList=[]
        findBaseSpaceLocationPageList(this.queryParams).then(response => {
            this.bclassList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      // 字典设备状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 字典设备状态字典翻译
      classDeptFormat(row, column) {
        return this.selectDictLabel(this.classDeptOptions, row.classDept);
      },
      // 班级状态修改
      handleStatusChange(row) {
          let text = row.status === "1" ? "启用" : "停用";
          this.$confirm('确认要 ' + text + ' "' + row.userName + '"吗?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
              return addOrUpdateIPassUser(row);
            }).then(() => {
              this.msgSuccess(text + "成功");
            }).catch(function() {
              row.userStatus = row.userStatus === "2" ? "1" : "2";
            });



      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
            locationPid:null,
            locationName:null,
            locationType:'6'
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        // if(this.queryParams.locationName){
        //     this.queryParams.locationPid=null
        // }else{
        //     this.queryParams.locationPid=0
        // }

        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");

        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        this.build();
        this.open = true;
        this.title = "添加空间位置";
        this.disabledInput=false;
        this.locationList=[]
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.build();
        this.open = true
        getLocationDetails(row.id).then(resp=>{
            this.form = resp.data
            this.form.locationPid = Number(resp.data.locationPid)
            this.locationList = resp.data.locationList
        })

      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          console.log("form",this.form)
          if (valid) {
            // this.form.level = this.form.levelName.split("-").length
            this.form.status=1
            this.form.locationList = this.locationList
            addOrUpdateBaseSpaceLocationInfo(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("提交成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.message);
                }
              });

          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除班级编号为"' + ids + '"的数据项?', "警告", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }).then(function() {
                  return deleteBaseSpaceLocationInfo(row);
                }).then(() => {
                  this.getList();
                  this.msgSuccess("删除成功");
                }).catch(function() {});

      },
      loadChildData(tree, treeNode, resolve){
        console.log(treeNode)
        console.log(tree)
        findBaseSpaceLocationPageList({pageNum:1,pageSize:1000,locationPid:tree.id}).then(response => {
            resolve(response.data.list)
          }
        );


      },
      inputSeat(val){
        console.log(val)
        // this.locationList=[]
        const length = this.locationList.length - val
        if(length<0){
          this.locationList.push({
                berthCode: this.locationList.length+1,
                berthType: '1'
            })
        }else{
          this.locationList.pop()
        }
        // for(let i=0;i<val;i++){
        //     this.locationList.push({
        //         berthCode: i+1,
        //         berthType: '1'
        //     })
        // }

      }
    }
  };
  </script>
